<template>
    <div>
        <div class="button-group">
            <el-button link type="primary" @click="handleBack">
                <el-icon>
                    <Back />
                </el-icon>
                返回
            </el-button>
            <el-button-group>
                <el-button type="primary" @click="O_Add(true)">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增审核计划
                </el-button>
            </el-button-group>
        </div>

        <!-- 表格 -->
        <el-table :data="P_Form.examines" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="status" label="审核状态" width="120">
                <template #default="{ row }">
                    <el-tag v-if="row.status == 0" type="info">待审核</el-tag>
                    <el-tag v-if="row.status == 1" type="success">已审核</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="examineDate" label="计划时间" width="120"/>
            <el-table-column prop="examineLevel" label="审核定级" width="120"/>
            <el-table-column prop="actualFinishingDate" label="完成时间" width="120" />
            <el-table-column prop="problem" label="问题描述" />
            <el-table-column label="计划文件">
                <template #default="{ row }">
                    <el-button v-for="file in row.annexFiles" :key="file.uploadFileId" link type="primary"
                        @click="downloadFile(file)">
                        {{ file.uploadFileName }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="审核文件">
                <template #default="{ row }">
                    <el-button v-for="file in row.reportFiles" :key="file.uploadFileId" link type="primary"
                        @click="downloadFile(file)">
                        {{ file.uploadFileName }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">详情</el-button>
                    <el-button link type="success" v-if="row.examineLevel && !row.status"
                        @click="handleExamine(row)">审核</el-button>
                    <el-button link type="danger" v-if="!row.examineLevel && !row.status"
                        @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 抽屉表单 -->
        <el-drawer @open="handleDrawerOpen" v-model="showDrawer" :title="showupload ? '新增审核计划' : '审核计划详情'" size="600px">
            <el-form ref="qualityFormRef" :model="qualityForm" label-width="120px">

                <el-form-item label="计划时间" prop="examineDate"
                    :rules="[{ required: true, message: '请选择计划时间', trigger: 'change' }]">
                    <el-date-picker :disabled="!D_type" v-model="qualityForm.examineDate" type="date"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择计划时间" style="width: 100%" />
                </el-form-item>

                <template v-if="!D_type">
                    <el-form-item label="完成时间" prop="actualFinishingDate"
                        :rules="[{ required: true, message: '请选择完成时间', trigger: 'change' }]">
                        <el-date-picker v-model="qualityForm.actualFinishingDate" type="date" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" placeholder="请选择完成时间" style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="审核定级" prop="examineLevel"
                        :rules="[{ required: true, message: '请选择审核定级', trigger: 'change' }]">
                        <el-select v-model="qualityForm.examineLevel" placeholder="请选择计划等级" style="width: 100%">
                            <el-option v-for="item in examineOptions" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="问题描述">
                        <el-input v-model="qualityForm.problem" type="textarea" placeholder="请输入问题描述"
                            style="width: 100%" />
                    </el-form-item>

                    <el-form-item label="审核报告" prop="reportFiles">
    <div style="width: 100%">
        <el-upload 
            v-if="!qualityForm.status" 
            class="upload-demo" 
            ref="reportUploadRef"
            action="#" 
            :auto-upload="false" 
            :on-change="handleReportFileChange"
          
            multiple 
            drag
        >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    <div>支持任意类型格式文件</div>
                </div>
            </template>
        </el-upload>
    </div>
    <div v-if="qualityForm.report?.length">
        <div v-for="(file, idx) in qualityForm.reportFiles" :key="file.uploadFileId" class="file-info">
            <el-icon @click="downloadFile(file)">
                <Document />
            </el-icon>
            <span @click="downloadFile(file)">{{ file.uploadFileName }}</span>
            <el-icon class="delete-icon" v-if="!qualityForm.status" @click="deleteReportFile(idx)">
                <Delete />
            </el-icon>
        </div>
    </div>
</el-form-item>


                    <el-form-item label="问题关闭证据" prop="files">
                        <!-- :rules="[{ required: true, message: '请上传计划文件', trigger: 'change' }]" -->
                        <div style="width: 100%">
                            <el-upload v-if="!qualityForm.status" class="upload-demo" ref="uploadRef"
                                action="/api/upload" :auto-upload="false" :on-success="handleUploadSuccess"
                                :on-error="handleUploadError" :on-change="handleFileChange"
                                multiple drag>
                                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                <div class="el-upload__text">
                                    将文件拖到此处，或<em>点击上传</em>
                                </div>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        <div>支持 任意类型 格式文件</div>
                                    </div>
                                </template>
                            </el-upload>
                        </div>
                        <div v-if="qualityForm.annexFiles?.length">
                            <div v-for="(file,idx) in qualityForm.annexFiles" :key="file.uploadFileId" class="file-info">
                                <el-icon @click="downloadFile(file)">
                                    <Document />
                                </el-icon>
                                <span @click="downloadFile(file)">{{ file.uploadFileName }}</span>

                                <el-icon class="delete-icon" v-if="!qualityForm.status" @click="O_Delete(idx)">
                                    <Delete />
                                </el-icon>
                            </div>
                        </div>
                    </el-form-item>
                </template>


                <div class="drawer-footer">
                    <el-button @click="showDrawer = false">取消</el-button>
                    <el-button type="primary" v-if="!qualityForm.status" @click="handleSubmit">确定</el-button>
                </div>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { storeToRefs, defineStore } from "pinia"
import P_store from "@store/supplierpro/index.js"


const P = P_store()
const { P_Form } = storeToRefs(P)
const R = useRouter()
const _G = defineStore('main', {})()
const _Id = ref(_G.M.GetId())

onMounted(() => {
    // P.Hp_GetAuditPlan(_Id.value)
})

const examineOptions = [
    'S', 'A', 'B', 'C', 'D'
]



const showupload = ref(false)
const D_type = ref(false)
const O_Add = (type) => {
    showDrawer.value = true
    showupload.value = true
    D_type.value = type
    qualityForm.value = {
        supplierId: _Id.value
    }
}


const showDrawer = ref(false)
const editingId = ref(null)
const formTitle = computed(() => editingId.value ? '编辑质量计划' : '新增质量计划')

const qualityForm = ref({
    files: [],
    supplierId: _Id.value
})


const qualityFormRef = ref(null)

const uploadRef = ref(null)


const handleFileChange = (uploadFile, uploadFiles) => {
    qualityForm.value.files = uploadFiles.map(file => ({
        name: file.name,
        url: file.url || '',
        raw: file.raw
    }))
}


const reportUploadRef = ref(null)

const handleReportFileChange = (uploadFile, uploadFiles) => {
    qualityForm.value.reportFiles = uploadFiles.map(file => ({
        name: file.name,
        url: file.url || '',
        raw: file.raw
    }))
}

const deleteReportFile = (idx) => {
    ElMessageBox.confirm('确认删除该文件？', '提示', {
        type: 'warning'
    }).then(() => {
        qualityForm.value.report.splice(idx, 1)
        qualityForm.value.reportFiles.splice(idx, 1)
        ElMessage.success('删除成功')
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}
const handleDrawerOpen = () => {
    if (D_type.value) return
    // 初始化上传文件
    qualityForm.value.files = []
    if (uploadRef.value) {
        uploadRef.value.clearFiles()
    }
}

const handleUploadSuccess = (response, file, uploadFiles) => {
    const targetFile = qualityForm.value.files.find(f => f.name === file.name)
    if (targetFile) {
        targetFile.url = response.fileUrl
    }
    ElMessage.success('上传成功')
}

const handleUploadError = () => {
    ElMessage.error('上传失败')
}



const handleSubmit = () => {
    qualityFormRef.value?.validate((valid) => {
        if (valid) {
            console.log('质量计划表单数据：', qualityForm.value)
            // return 
            showDrawer.value = false
            if (D_type.value) {
                P.Hp_SevaAuditPlanNew(qualityForm.value)
            } else {
                const { files,reportFiles,report, supplierId, examineDate, examineLevel, examineId, actualFinishingDate, problem, annex } = qualityForm.value
                P.Hp_SevaAuditPlanSupplement({ annex, files,reportFiles,report, supplierId, examineDate, examineLevel, examineId, actualFinishingDate, problem })
            }
            // TODO: 调用保存接口
        } else {
            ElMessage.error('请填写完整信息')
            return false
        }
    })
}

const handleEdit = (row) => {
    showupload.value = false
    editingId.value = row.id
    D_type.value = false
    Object.assign(qualityForm.value, row)
    showDrawer.value = true
}

const handleDelete = (row) => {

    ElMessageBox.confirm('确认删除该计划？', '提示', {
        type: 'warning'
    }).then(() => {
        // TODO: 调用删除接口
        // ElMessage.success('删除成功')
        P.Hp_DelAuditPlan(row.examineId)
    })
}

const downloadFile = (file) => {
    // window.open(file.url)
    P.Hp_Download(file.uploadFileId)
}

const handleBack = () => {
    R.push('/supplierpro')
}


const handleExamine = (row) => {
    console.log(row);

    ElMessageBox.confirm('确认审核该协议？', '提示', {
        type: 'warning'
    }).then(() => {
        P.Hp_GetAuditPlanNew(row.examineId)
    })
}


const O_Delete = (idx) => {
    ElMessageBox.confirm('确认删除该文件？', '提示', {
        type: 'warning'
    }).then(() => {
        qualityForm.value.annex.splice(idx, 1)
        qualityForm.value.annexFiles.splice(idx, 1)
        
            ElMessage.success('删除成功')
        
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

</script>

<style lang="less" scoped>
.delete-icon {
    color: #f56c6c;
    cursor: pointer;
    margin-left: auto;
    
    &:hover {
        color: #ff7875;
    }
}
.button-group {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.drawer-form {
    padding: 20px;
}

.file-info {
    padding: 12px 16px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.3s;
    color: #409eff;

    &:hover {
        border-color: #409eff;
        color: #79bbff;
    }

    .el-icon {
        font-size: 18px;
    }
}

.drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    text-align: right;
    background: #fff;
    border-top: 1px solid #dcdfe6;
}

:deep(.upload-demo) {
    .el-upload {
        width: 100%;
    }

    .el-upload-dragger {
        width: 100%;
    }

    .el-upload__tip {
        line-height: 1.2;
        padding: 4px 0;
        color: #909399;
    }
}

.file-info {
    margin-bottom: 8px;

    &:last-child {
        margin-bottom: 0;
    }
}
</style>